<?php
/**
 * Created by PhpStorm.
 * Script Name: Onmessage.php
 * Create: 2023/3/18 10:57
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\wap\controller;

use plugin\wechat\app\model\MpFollow;
use plugin\wechat\app\MpController;
use support\Request;

class Onmessage extends MpController
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 微信网页授权
     * @param Request $request
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    function wxAuth(Request $request){
        // http://easywechat.org/oauth_callback
        $oauth = $this->mpApp->oauth;
        // 获取 OAuth 授权结果用户信息
        $code = $request->input('code');
        $user = $oauth->userFromCode($code)->toArray()['raw'];

        $mp_info = $request->mpInfo;
        $original_data = [
            'company_id'          => $mp_info['company_id'],
            'mp_id'          => $mp_info['id'],
            'openid'        => $user['openid'],
            'nickname'      => $user['nickname'],
            'sex'           => $user['sex'] ?? 1,
            'headimgurl'    => $user['headimgurl'],
            'city'          => $user['city'],
            'province'      => $user['province'],
            'country'       => $user['country'],
            'unionid'       => $user['unionid'] ?? '',
            'subscribe_time' => $user['subscribe_time'] ?? 0,
            'subscribe_scene' => $user['subscribe_scene'] ?? ''
        ];

        $follow = MpFollow::where([
            ['company_id','=', $mp_info['company_id']],
            ['mp_id' ,'=', $mp_info['id']],
            ['openid','=', $original_data['openid']]
        ])->find();

        if($follow){
            MpFollow::update(array_merge([
                'id' => $follow['id']
            ], $original_data));
        }else{
            MpFollow::create($original_data);
        }
        session([SESSION_MP_FOLLOW => $original_data]);
        $target_url = session('target_url');
        return redirect($target_url);
    }
}